package com.wyp.didishige.activity.users;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.wyp.didishige.activity.UserInfoActivity;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.StringUtils;
import com.wyp.didishige.wiget.xlist.XListView;
import com.wyp.didishige.R;
import com.wyp.didishige.activity.BaseActivity;
import com.wyp.didishige.adapter.NearPeopleAdapter;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.LogUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

/**
 * 附近的人列表
 *
 * @author smile
 * @ClassName: NewFriendActivity
 * @Description: TODO
 * @date 2014-6-6 下午4:28:09
 */
public class CommunityUsersActivity extends BaseActivity implements XListView.IXListViewListener, OnItemClickListener {

    XListView mListView;
    NearPeopleAdapter adapter;
    List<User> nears = new ArrayList<User>();
    User user;
    private SwipeRefreshLayout hullSwipe = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_people);
        init();
    }

    @Override
    protected void initParamter() {
        super.initParamter();
        adapter = new NearPeopleAdapter(this, nears);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            user = (User) bundle.getSerializable(Config.KEY_USER);
        }
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        if (!StringUtils.isNullOrEmpty(user.getCommunity())) {
            actionBar.setTitle(user.getCommunity());
        }

        hullSwipe = (SwipeRefreshLayout) findViewById(R.id.hullSwipe);
        mListView = (XListView) findViewById(R.id.list_near);
    }

    @Override
    protected void initWidgetState() {
        super.initWidgetState();
        hullSwipe.setColorSchemeResources(R.color.btn_blue, R.color.vip_male);
        hullSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                getList(true);
            }
        });
        hullSwipe.setRefreshing(true);

        mListView.setAdapter(adapter);

        mListView.startLoadMore();
    }

    @Override
    protected void initWidgetListener() {
        super.initWidgetListener();
        mListView.setOnItemClickListener(this);

        mListView.setPullLoadEnable(true);
        // 允许下拉
        mListView.setPullRefreshEnable(false);

        // 设置监听器
        mListView.setXListViewListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        User user = (User) adapter.getItem(position);
        Bundle bundle = new Bundle();

        bundle.putString(Config.KEY_USER_ID, user.getObjectId());
        IntentUtil.start_activity(CommunityUsersActivity.this, UserInfoActivity.class, bundle);
    }

    private void refreshLoad() {
        mListView.stopLoadMore();
        mListView.stopRefresh();
    }

    @Override
    public void onRefresh() {
        page = 0;
        getList(true);
    }

    @Override
    public void onLoadMore() {
        getList(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    int page = 0;
    int limit = 20;

    private void getList(final boolean isRefresh) {
        BmobQuery<User> query = new BmobQuery<User>();
        if (user.getCommunityUsers() == null) {
            refreshLoad();
            mListView.setFooterText("暂无用户");
            return;
        }

        String[] ids = new String[user.getCommunityUsers().size()];
        for (int i = 0; i < user.getCommunityUsers().size(); i++) {
            ids[i] = user.getCommunityUsers().get(i);
        }
        query.setLimit(limit);
        query.setSkip(limit * page);
        query.order("-updatedAt");
        query.addWhereContainedIn("objectId", Arrays.asList(ids));
        query.findObjects(this, new FindListener<User>() {
            @Override
            public void onSuccess(List<User> list) {
                refreshLoad();

                resetBottom(list,isRefresh);

                if (isRefresh) {
                    adapter.setList(list);
                } else {
                    adapter.addAll(list);
                }
                page++;

            }

            @Override
            public void onFinish() {
                super.onFinish();
                hullSwipe.setRefreshing(false);

            }

            @Override
            public void onError(int i, String s) {
                LogUtil.d("error", s);
                refreshLoad();
            }
        });
    }

    /**
     * 设置listview底部显示方式
     */
    private void resetBottom(List<User> list,boolean isRefresh){
        if (list != null&&!list.isEmpty()) {
            if (list.size()<limit) {
                mListView.setPullLoadEnable(false);
            }
        }else{
            if (isRefresh){
                mListView.setFooterText("暂无用户");
            }else{
                mListView.setPullLoadEnable(false);
            }

        }
    }
}
